package com.zzyl.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.zzyl.dto.LoginDto;
import com.zzyl.entity.SysUser;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.LoginMapper;
import com.zzyl.properties.JwtProperties;
import com.zzyl.service.LoginService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import static com.zzyl.enums.BasicEnum.LOGIN_PASSWORD_FAIL;
import static com.zzyl.enums.BasicEnum.LOGIN_USERNAME_FAIL;

@Service
public class LoginServiceImlp implements LoginService {
    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public UserVo login(LoginDto loginDto) {
        SysUser sysUser= loginMapper.getUserByUserName(loginDto);
        if (sysUser==null){
            throw new  BaseException(LOGIN_USERNAME_FAIL);
        }else {
            if (!BCrypt.checkpw(loginDto.getPassword(), sysUser.getPassword())){
                throw new  BaseException(LOGIN_PASSWORD_FAIL);
            }
            UserVo userVo = new UserVo();
            Map<String,Object> map = new HashMap<>();
            map.put("username",loginDto.getUsername());
            BeanUtils.copyProperties(loginDto,userVo);
//            userVo.setUserToken(JwtUtil.createJWT("itheima",600000,map));
            userVo.setUserToken(JwtUtil.createJWT(jwtProperties.getBase64EncodedSecretKey(),jwtProperties.getTtl(),map));
            return userVo;
        }
    }
}
